/**
 * 心情信封
 */
var mongodb=require('./db');
var markdown=require('markdown').markdown;
function Xinfeng(name,email,content) {
    this.name=name,
    this.email=email,
    this.content=content
}
module.exports=Xinfeng;
//保存心情日记
Xinfeng.prototype.save=function (callback) {
    var date=new Date();
    var query={
        name:this.name,
        email:this.email,
        content:this.content,
        date:date.getFullYear()+'-'+((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+
            (date.getDate()<10?'0'+date.getDate():date.getDate()),
        second:date.getFullYear()+'-'+((date.getMonth()+1)<10?'0'+(date.getMonth()+1):(date.getMonth()+1))+'-'+
            (date.getDate()<10?'0'+date.getDate():date.getDate())+' '+(date.getHours()<10?'0'+date.getHours():date.getHours())+
            ':'+(date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes())+':'+(date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds())
    }
    mongodb.open(function (err,db) {
        if(err){
            return callback(err);
        }
        db.collection('xinqings',function (err,collection) {
            if(err){
                mongodb.close();
                return callback(err);
            }
            collection.insert(query,function (err) {
                mongodb.close();
                if(err){
                    return callback(err);
                }
                return callback(null);
            })
        })
    })
}
//查询
Xinfeng.get=function (name,callback) {
    var query={name:name};
    mongodb.open(function (err,db) {
        if(err){
            return callback(err);
        }
        db.collection('xinqings',function (err,collection) {
            if(err){
                mongodb.close();
                return callback(err);
            }
            collection.find(query).sort({second:-1}).toArray(function (err,xinfengs) {
                mongodb.close();
                if(err){
                    return callback(err);
                }
                //查询成功
                xinfengs.forEach(function (xinfeng,index) {
                    xinfeng.content=markdown.toHTML(xinfeng.content);
                });
                return callback(null,xinfengs);
            })
        })
    })

}
